package com.example.demo.util;

import java.util.Date;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

public class TokenUtil {
//  public final static String JWT_PREFIX = "Bearer ";

  private final static String SECRET_KEY = "9y?un@&YZxaI9'0H%P9V?,]7";

  private static final long EXPIRE_TIME = 60 * 60 * 1000;  // 过期 时间  30 分钟

  public static String createJWT(int userId, String username){

      Date date =new Date(System.currentTimeMillis()+EXPIRE_TIME);
      return

              Jwts.builder()
//              .setId(jwtId)
//              .setSubject(subject)
              .claim("userId", userId)
              .claim("username", username)
              .setIssuedAt(new Date(System.currentTimeMillis()))
//              .setIssuer() // 签发者
//              .setNotBefore() // 失效时间
//              .setExpiration() // 过期时间
//              .setExpiration(date)
              .signWith(SignatureAlgorithm.HS256, SECRET_KEY)
              .compact();
  }



  public static Claims parserJWT(String token){
      Claims claims;
      try {
          claims = Jwts.parser()
                  .setSigningKey(SECRET_KEY)
                  .parseClaimsJws(token)
//                  .parseClaimsJws(token.replace(JWT_PREFIX,""))
                  .getBody();
      } catch (Exception e) {
          claims = null;
      }
      return claims;
  }

  public static void main(String[] args) {
      String token = createJWT(1,"你好");
//      System.out.println(createJWT(1,"你好",1,1).length());
//      Claims claims = parserJWT(token);
//      System.out.println(claims);
//      System.out.println(claims.get("userId"));
//      System.out.println(claims.get("username"));
//      System.out.println(claims.get("isSuperAdmin"));
//      System.out.println(claims.get("organizationId"));
//      Date expiration = claims.getExpiration();
//      System.out.println(expiration);
//      long time = expiration.getTime();
//      long millis = System.currentTimeMillis();
//      System.out.println(time - millis);
//      System.out.println(EXPIRE_TIME);
  }
}
